import 'package:built_collection/built_collection.dart';
import 'package:mobile_app.core/core/domain/entities/learning_content/collection_list_item/collection_list_item.dart';

abstract class ApplyCustomCollectionListItemDeletion {
  BuiltList<CollectionListItem> call({
    required String customCollectionListItemId,
    required BuiltList<CollectionListItem> collectionListItems,
  });
}

class ApplyCustomCollectionListItemDeletionImpl implements ApplyCustomCollectionListItemDeletion {
  const ApplyCustomCollectionListItemDeletionImpl();

  @override
  BuiltList<CollectionListItem> call({
    required String customCollectionListItemId,
    required BuiltList<CollectionListItem> collectionListItems,
  }) {
    final updatedCollectionListItems = <CollectionListItem>[];

    for (final collectionListItem in collectionListItems) {
      if (collectionListItem is InbuiltCollectionListItem) {
        final inbuiltCollectionListItem = collectionListItem;

        updatedCollectionListItems.add(inbuiltCollectionListItem);
      } else if (collectionListItem is CustomCollection) {
        final customCollection = collectionListItem;

        if (customCollectionListItemId != customCollection.id) {
          updatedCollectionListItems.add(customCollection);
        }
      } else if (collectionListItem is CustomCollectionFolder) {
        final customCollectionFolder = collectionListItem;

        if (customCollectionListItemId != customCollectionFolder.id) {
          final updatedCollections = customCollectionFolder.collections.where((customCollection) {
            return customCollectionListItemId != customCollection.id;
          }).toBuiltList();

          final updatedCustomCollectionFolder = customCollectionFolder.copyWith(
            collections: () => updatedCollections,
          );

          updatedCollectionListItems.add(updatedCustomCollectionFolder);
        }
      }
    }

    return updatedCollectionListItems.build();
  }
}
